package org.dromara.system.controller.system;

import lombok.RequiredArgsConstructor;
import cn.dev33.satoken.annotation.SaIgnore;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.dromara.system.domain.bo.SysFaultFeedbackBo;
import org.dromara.system.domain.bo.SysFaultFeedbackQueryBo;
import org.dromara.system.domain.bo.SysFaultInfoQueryBo;
import org.dromara.system.domain.vo.SysFaultFeedbackVo;
import org.dromara.system.domain.vo.SysFaultInfoVo;
import org.dromara.system.service.ISysFaultFeedbackService;
import org.dromara.system.service.ISysFaultInfoService;
import org.dromara.system.service.ISysSolutionDocService;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 故障查询（用户端） 控制层
 * 用户端查询无需权限验证，提供公开的故障信息查询服务
 *
 * @author system
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/user/fault")
@SaIgnore
public class SysFaultQueryController extends BaseController {

    private final ISysFaultInfoService faultInfoService;
    private final ISysSolutionDocService solutionDocService;
    private final ISysFaultFeedbackService faultFeedbackService;

    /**
     * 第一级查询：获取所有挖掘机机型列表
     */
    @GetMapping("/models")
    public R<List<String>> getExcavatorModels() {
        List<String> models = faultInfoService.getExcavatorModelList();
        return R.ok(models);
    }

    /**
     * 第二级查询：根据机型获取故障部分列表
     */
    @GetMapping("/parts")
    public R<List<String>> getFaultParts(@RequestParam(required = false) String excavatorModel) {
        List<String> parts = faultInfoService.getFaultPartList(excavatorModel);
        return R.ok(parts);
    }

    /**
     * 第三级查询：根据机型和故障部分获取故障现象列表
     */
    @GetMapping("/symptoms")
    public R<List<String>> getFaultSymptoms(@RequestParam(required = false) String excavatorModel,
                                           @RequestParam(required = false) String faultPart) {
        List<String> symptoms = faultInfoService.getFaultSymptomList(excavatorModel, faultPart);
        return R.ok(symptoms);
    }

    /**
     * 第四级查询-故障详情查询：根据机型、故障部分、故障现象获取故障详情
     */
    @GetMapping("/details")
    public R<List<Map<String, Object>>> getFaultDetails(@RequestParam(required = false) String excavatorModel,
                                                        @RequestParam(required = false) String faultPart,
                                                        @RequestParam(required = false) String faultSymptom) {
        List<Map<String, Object>> details = faultInfoService.getFaultDetailList(excavatorModel, faultPart, faultSymptom);
        return R.ok(details);
    }

    /**
     * 多条件查询：支持任意级别的条件组合查询故障信息
     * 支持单级别查询：只选机型、只选机型+部分、只选机型+部分+现象等
     * 支持故障详情模糊查询：faultDetail参数在故障详情和备注中搜索
     */
    @GetMapping("/search")
    public TableDataInfo<SysFaultInfoVo> searchFaults(SysFaultInfoQueryBo queryBo, PageQuery pageQuery) {
        return faultInfoService.queryPageList(queryBo, pageQuery);
    }

    /**
     * 获取单个故障信息详情（包含解决方案）
     */
    @GetMapping("/{faultId}")
    public R<SysFaultInfoVo> getFaultInfo(@PathVariable Long faultId) {
        SysFaultInfoVo faultInfo = faultInfoService.queryById(faultId);
        return R.ok(faultInfo);
    }

    /**
     * 预览解决方案主PDF
     */
    @GetMapping("/solution/preview/{faultId}")
    public void previewSolutionDoc(@PathVariable Long faultId,
                                  HttpServletResponse response) throws Exception {
        // 通过故障ID获取对应的解决方案文档并预览
        SysFaultInfoVo faultInfo = faultInfoService.queryById(faultId);
        if (faultInfo != null && faultInfo.getSolutionId() != null) {
            solutionDocService.previewDocument(faultInfo.getSolutionId(), "inline", response);
        } else {
            throw new RuntimeException("故障信息不存在或无解决方案文档");
        }
    }

    // ==================== 故障反馈接口 ====================

    /**
     * 提交故障反馈（用户端）
     * 支持上传最多3张图片
     */
    @RepeatSubmit()
    @PostMapping(value = "/feedback", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<SysFaultFeedbackVo> submitFeedback(
        @RequestPart("feedback") @Validated(AddGroup.class) SysFaultFeedbackBo feedbackBo,
        @RequestPart(value = "images", required = false) MultipartFile[] images) {

        SysFaultFeedbackVo vo = faultFeedbackService.submitFeedback(feedbackBo, images);
        return R.ok("提交成功，请等待审核", vo);
    }

    /**
     * 查询我的反馈列表（需登录）
     */
    @GetMapping("/feedback/my")
    public TableDataInfo<SysFaultFeedbackVo> myFeedbacks(
        SysFaultFeedbackQueryBo queryBo, PageQuery pageQuery) {

        try {
            // 限制只查询当前用户的反馈
            queryBo.setCreateUserId(LoginHelper.getUserId());
        } catch (Exception e) {
            // 未登录则返回空列表
            return TableDataInfo.build();
        }
        return faultFeedbackService.queryPageList(queryBo, pageQuery);
    }

    /**
     * 查询单条反馈详情
     */
    @GetMapping("/feedback/{feedbackId}")
    public R<SysFaultFeedbackVo> getFeedbackInfo(@PathVariable Long feedbackId) {
        SysFaultFeedbackVo vo = faultFeedbackService.queryById(feedbackId);
        return R.ok(vo);
    }
}
